#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : Chestnut
# @time    : 2025/6/26 09:56
# @function: What can I do.
# @version : V1
import csv
import os.path
import tkinter
from tkinter import filedialog, Tk, ttk


# 定义TXT文件路径和CSV文件路径
class TransExtendName:
    def __init__(self):
        self.t_files = []

    def read_file(self):
        self.t1.delete("1.0", tkinter.END)
        txt_files = filedialog.askopenfilenames(filetypes=[
            ("文本文件", "*.txt"),
            ("所有文件", "*.*")
        ])
        if len(txt_files) == 0:
            self.t1.insert(tkinter.END, "No Files Selected")
            pass
        else:
            for txt_file in txt_files:
                self.t1.insert(tkinter.END, txt_file + "\n")
            self.t1.insert(tkinter.END, f"共选择{len(txt_files)}个文件")
            self.file_name.set(txt_files[0])
            self.t_files = txt_files

    def transExtendName(self):
        self.t1.delete("1.0", tkinter.END)
        for txt_file in self.t_files:
            csv_file = txt_file[0:-4] + ".csv"
            with open(txt_file, 'r') as txt, open(csv_file, 'w', newline='') as csvfile:
                writer = csv.writer(csvfile)
                content = txt.readlines()
                self.p1.config(maximum=len(content))
                for count, line in enumerate(content):
                    row = line.strip().strip("#").split(',')
                    writer.writerow(row)
                    self.p1['value'] = count + 1
                    self.p1.update()
                self.t1.insert(tkinter.END,
                               os.path.basename(txt_file) + "-->" + os.path.basename(csv_file) + " Done!\n")
        self.t1.insert(tkinter.END, f"共转化了{len(self.t_files)}个文件")

    def main_window(self):
        root = Tk()
        self.file_name = tkinter.StringVar()
        root.title("Transform TXT ExtendName")
        tkinter.Label(root, text="选择文件").grid(row=0, column=0)
        self.e1 = tkinter.Entry(root, width=50, textvariable=self.file_name)
        self.t1 = tkinter.Text(root)
        tkinter.Button(root, text="Browse", command=self.read_file).grid(row=0, column=2)
        tkinter.Button(root, text="Start", command=self.transExtendName, width=80).grid(row=3, column=0, columnspan=3)
        self.p1 = ttk.Progressbar(root, orient=tkinter.HORIZONTAL, length=550, mode='determinate')
        root.bind("<Return>", self.transExtendName)
        self.e1.grid(row=0, column=1)
        self.t1.grid(row=1, column=0, columnspan=3)
        self.p1.grid(row=2, column=0, columnspan=3)
        root.mainloop()


myapp = TransExtendName()
myapp.main_window()
